package com.etlmaster.executor.steps.loop;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import com.etlmaster.executor.utils.DpVfsUtils;
import com.etlmaster.executor.utils.StepState;
/**
 * @author Wugf
 * @date 2016-03-08
 */
public class FileLoopProcessor extends LoopProcessor {

	@Override
	public int process() throws InterruptedException, ExecutionException {
		int posi = expression.indexOf(" open ");
		String variableName = expression.substring(0, posi);
		String sqlStatement = expression.substring(posi + 4,
				expression.length());

		FileObject fileObject = DpVfsUtils.getInstance().resolveFile(
				sqlStatement);
		try {
			if (fileObject.getType() == FileType.FILE) {
				InputStream in = fileObject.getContent().getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));
				try {
					if (reader != null) {
						String rowData = null;
						while ((rowData = reader.readLine()) != null) {
							i++;
				    		
				    		job.putVariable(variableName, rowData);
							Boolean isBreak = (Boolean) job
									.getVariable("isBreak");
							if ((isBreak != null
									&& (Boolean) job.getVariable("isBreak"))||loopStep instanceof EndLoopStep) {
								break;
							}
							loopStepMeta.runLoop(job,i,"i");
							
							
						}
						loopStepMeta.startLoopStack();
						
					}
				} catch (IOException e) {
					loopStepMeta.log("ERROR","文件读取异常，{}",e.getMessage());
					return StepState.RUNNING_FAILED;
				}  finally {
					try {
						reader.close();
						in.close();
					} catch (IOException e) {
						loopStepMeta.log("ERROR","关闭文件对象异常，{}",e.getMessage());
						return StepState.RUNNING_FAILED;
					}
					DpVfsUtils.getInstance().closeFileObject(fileObject);
				}
			}
		} catch (FileSystemException e) {
			loopStepMeta.log("ERROR","文件读取异常，{}",e.getMessage());
			return StepState.RUNNING_FAILED;
		}
		return StepState.RUNNING_SUCCESSED;

	}

}
